<template>
  <div>
    <div style="height:50px; line-height: 50px; border-bottom: 1px solid #E4E4E4; background-color:#f3f3f3">
      <p style="margin-left: 20px;">修改商品</p>
    </div>
    <div style="height:20px; background-color:#f9f9f9">
      &nbsp;
    </div>
    <div style="background-color: #FFFFFF;">
      <el-row>
        <el-col :span="3" style="height:1900px; border-top: 1px solid #E4E4E4;">
          <div
            style=" width:200px;height:45px; background-image: url('src/assets/goodsImg/u12495.png'); margin-top:40px"
            z-index="11" background-size: cover>
            <p style="margin-left: 20px; line-height: 45px;">商品分类</p>
          </div>

          <div
            style=" width:200px;height:45px; background-image: url('src/assets/goodsImg/u12495.png'); margin-top:380px"
            z-index="11">
            <p style="margin-left: 20px; line-height: 45px;">价格策略</p>
          </div>

          <div
            style=" width:200px;height:45px; background-image: url('src/assets/goodsImg/u12495.png'); margin-top:350px"
            z-index="11">
            <p style="margin-left: 20px; line-height: 45px;">仓库初期设置</p>
          </div>

          <div
            style=" width:200px;height:45px; background-image: url('src/assets/goodsImg/u12495.png'); margin-top:220px"
            z-index="11">
            <p style="margin-left: 20px; line-height: 45px;">仓库预警</p>
          </div>

          <div
            style=" width:200px;height:45px; background-image: url('src/assets/goodsImg/u12495.png'); margin-top:220px"
            z-index="11">
            <p style="margin-left: 20px; line-height: 45px;">图片管理</p>
          </div>
        </el-col>
        <el-col :span="18" style="height:1900px;border: 1px solid #E4E4E4;">
          <div>
            <el-form ref="ruleFormref" style="max-width: 600px;margin-top: 30px; margin-left: 50px;"
              :model="purchaseForm" label-width="100px">

              <el-form-item label="商品分类:" prop="name">
                <el-cascader ref="casref" :props="casconfig" v-model="purchaseForm.categoryName"
                  :options="categoryOptions" @change="handleChange" placeholder="请选择分类" />
              </el-form-item>

              <el-form-item label="商品名称:">
                <el-input v-model="purchaseForm.name" placeholder="请输入商品名称" />
              </el-form-item>

              <el-form-item label="规格型号:">
                <el-input v-model="purchaseForm.spec" placeholder="请输入规格型号" />
              </el-form-item>

              <el-form-item label="商品编码:">
                <el-input v-model="purchaseForm.code" placeholder="请输入商品编码" />
              </el-form-item>

              <el-form-item label="计量单位:">
                <el-select v-model="purchaseForm.unit" clearable placeholder="请选择单位" style="width: 240px">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="商品条码:">
                <el-input v-model="purchaseForm.barcode" placeholder="请输入商品条码" />
              </el-form-item>

              <el-form-item label="首选仓库:">
                <el-select v-model="purchaseForm.warehouseId" clearable placeholder="请选择仓库" style="width: 240px">
                  <el-option v-for="item in warehouse" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>

              <el-form-item label="零售价格:" style="margin-top:100px">
                <el-input v-model="purchaseForm.price" placeholder="请输入商品售价" />
              </el-form-item>
              <el-form-item label="批发价:">
                <el-input v-model="purchaseForm.batchPrice" placeholder="请输入商品批发价" />
              </el-form-item>
              <el-form-item label="vip客户价:">
                <el-input v-model="purchaseForm.vipPrice" placeholder="请输入商品vip客户价" />
              </el-form-item>
              <el-form-item label="折扣率一 (%):">
                <el-input v-model="purchaseForm.rateOne" placeholder="请输入商品折扣率" />
              </el-form-item>
              <el-form-item label="折扣率二 (%):">
                <el-input v-model="purchaseForm.rateTwo" placeholder="请输入商品折扣率" />
              </el-form-item>
              <el-form-item label="预计采购价:">
                <el-input v-model="purchaseForm.purchasePrice" placeholder="请输入商品预计采购价" />
              </el-form-item>

              <div class="detail">
                <!--明细-->
                <div class="detail-title">
                  <span>采购明细</span>
                  <el-button type="primary" size="small" @click="addRow" style="margin-left:10px">增行</el-button>
                  <el-button type="primary" size="small" @click="delRow">删行</el-button>
                </div>
                <!--列表-->
                <el-table :data="tableData" style="width: 100%" stripe border @cell-click="cellck" ref="purchaseRef">
                  <el-table-column type="selection" width="50" header-algin="center" align="center" />
                  <el-table-column type="index" label="序号" width="70" header-algin="center" align="center" />

                  <el-table-column prop="name" label="仓库" header-algin="center" align="center">
                    <template v-slot="{ row, column }">
                      <span v-if="row.show[column.property] == undefined">{{ row.goodsname }}</span>
                      <el-input v-else v-model="row.goodsname" placeholder="点击选择仓库"
                        @click="isshowchoose = true"></el-input>
                    </template>
                  </el-table-column>


                  <el-table-column prop="num" label="期初数量" width="150" header-algin="center" align="center">
                    <template v-slot="{ row, column }">
                      <span v-if="row.show[column.property] == undefined">{{
                        row.num
                      }}</span>
                      <el-input-number v-else v-model="row.num" size="small" :min="0"></el-input-number>
                    </template>
                  </el-table-column>


                  <el-table-column prop="price" label="单位成本" width="150" header-algin="center" align="center">
                    <template v-slot="{ row, column }">
                      <span v-if="row.show[column.property] == undefined">{{
                        row.price
                      }}</span>
                      <el-input-number v-else v-model="row.price" size="small" :min="0"
                        :precision="2"></el-input-number>
                    </template>
                  </el-table-column>

                  <el-table-column prop="total" label="期初总价" width="100" header-algin="center" align="center" />

                </el-table>
              </div>


              <div style="margin-top: 100px">
                <el-radio-group v-model="purchaseForm.isWarning" class="ml-4">
                  <el-radio value="2" size="large">启用分仓预警</el-radio>
                  <el-radio value="1" size="large">不启用分仓预警</el-radio>
                </el-radio-group>
              </div>

              <el-form-item label="最低库存:" style="width:300px">
                <el-input v-model="purchaseForm.lowStock" placeholder="请输入最低库存" />
              </el-form-item>

              <el-form-item label="最高库存:" style="width:300px">
                <el-input v-model="purchaseForm.heightStock" placeholder="请输入最高库存" />
              </el-form-item>

              <div style="margin-left: 20px; margin-top: 300px;">
                <el-button type="primary">上传图片</el-button>
              </div>
              <div style="margin-top: 260px">

              </div>
              <el-button type="primary" style="width: 160px; height: 40px; margin-left: 350px;"
                @click="save()">完成,提交商品</el-button>
              <el-button>取消</el-button>
            </el-form>
          </div>
        </el-col>
        <el-col :span="3" style="height:1684px; border-top: 1px solid #E4E4E4;"></el-col>
      </el-row>

      <!--  选择商品  -->
      <WarehouseBox :visible="isshowchoose" @choose="choose" @close="isshowchoose = false"></WarehouseBox>
    </div>
  </div>
</template>

<script setup>

import { ref, onMounted, watch } from 'vue'
import { getTree, queryWarehouse, savePurchase, get, updateGoods } from "@/api/goods/list";
import { ElMessage } from "element-plus";
import WarehouseBox from "@/views/goodsManage/WarehouseBox.vue"
import { getUser } from "@/utils/session";
import axios from "axios";
import { useRoute } from 'vue-router'

//配置选项
const casconfig = { value: "code", label: "name" };
const casref = ref(null);
//获取路由参数
const route = useRoute();


//仓库初期设置
const tableData = ref([])

//初始化2行
function init() {
  for (let i = 1; i <= 2; i++) {
    addRow()
  }
}

function addRow() {
  tableData.value.push({
    name: "",
    num: 0,
    price: 0,
    total: 0.00,
    show: {}
  })
}


//单元格双击事件
const lastRow = ref({})//记录上一次双击的是哪一行
function cellck(row, column) {
  //先清空之前添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
  let tmp = column.property;
  row.show[tmp] = true;
  //记录双击的行
  lastRow.value = row;
}


//删除行
const purchaseRef = ref(null)//表格引用
function delRow() {
  let rows = purchaseRef.value.getSelectionRows()
  if (rows.length == 0) {
    ElMessage({
      message: "请选择要删除的行！",
      type: "warning"
    });
  }
  rows.forEach(r => {
    removeData(r)
  })
}

//从tableData移除行，r代表要移除的行
function removeData(r) {
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //获取当前行对象
    let tmp = tableData.value[i];
    //判断tmp是否是要删除的对象r
    if (tmp == r) {
      tableData.value.splice(i, 1);
      break;//中止循环
    }
  }
}



//新增保存
async function save() {
  let detail = [];//保存用户填写的明细
  //便利表格数据
  tableData.value.forEach(r => {
    //判断当前对象中是否选择了商品 如果是，加入到明细
    if (r.goodsname != undefined && r.goodsname != "") {
      detail.push(r)
    }
  })
  if (detail.length == 0) {
    ElMessage({
      message: "仓库选择不能为空!",
      type: "warning"
    })
    return
  }
  //参数值
  let data = purchaseForm.value;//采购单基本信息
  //将明细加入采购单
  data.warehouseGoodsList = detail;
  //保存
  let res = await updateGoods(data);
  if (res.code == 200) {
    ElMessage({
      message: "修改成功",
      type: "success"
    })
    route.push({ path: "/goods/list" })
  }
}
//侦听器
watch(tableData, (n) => {
  //遍历表格明细 期初总价
  tableData.value.forEach(row => {

    if (row.num > 0 && row.price > 0) {
      //未优惠前总金额
      let total = row.num * row.price;
      row.total = total;
    }
  });
}, {
  deep: true
});
//商品选择
const isshowchoose = ref(false);//是否显示商品选择框
//选择商品
function choose(rows) {
  if (rows.length == 0) {
    return
  }
  //获取选择行的索引
  let index = -1;
  //遍历表格数据，查询选择的第一个对象的未知
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //临时对象
    let tmp = tableData.value[i];
    if (tmp == lastRow.value) {
      index = i;
      break;
    }
  }
  if (index == -1)
    return;
  //遍历选择的仓库
  for (let i = 0, len = rows.length; i < len; i++) {
    //临时对象
    let obj = tableData.value[index];
    obj.goodsId = rows[i].id;
    obj.goodsname = rows[i].name;
    obj.price = rows[i].price;
    obj.unit = rows[i].unit;
    obj.warehouse = rows[i].warehouseName;
    obj.wid = rows[i].warehouseId;
    index++;
  }
  //先清空之前添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
}



const options = [
  {
    value: '台',
    label: '台',
  },
  {
    value: '个',
    label: '个',
  },
  {
    value: '辆',
    label: '辆',
  },
  {
    value: '颗',
    label: '颗',
  },
  {
    value: '瓶',
    label: '瓶',
  }
]

const warehouse = ref([]);

//列表数据
const purchaseForm = ref({
  categoryCode: "",
  categoryName: "",
  name: "",
  spec: "",
  code: "",
  unit: "",
  barcode: "",
  warehouseId: "",
  price: "",
  batchPrice: "",
  vipPrice: "",
  rateOne: "",
  rateTwo: "",
  purchasePrice: "",
  isWarning: "",
  lowStock: "",
  heightStock: "",
  eid: getUser().eid,
  contracts: []
})

const categoryOptions = ref([])

//企业类目树
async function queryCategory() {
  let res = await getTree();
  if (res.code == 200) {
    categoryOptions.value = res.data
  }
}


let data = {
  "eid": getUser().eid
}
//查询仓库名称
async function queryWarehouseName() {

  let res = await queryWarehouse(data);
  if (res.code == 200) {
    warehouse.value = res.data
  }
}


//新增赋值
function handleChange(v) {
  let len = v.length - 1;
  purchaseForm.value.categoryCode = v[len];
  let tmp = casref.value.getCheckedNodes();
  purchaseForm.value.categoryName = tmp[0].label;
}


//查询详情方法
async function getBatch(id) {
  let res = await get(id);
  if (res.code == 200) {
    purchaseForm.value = res.data
    //获取明细
    let tmp = res.data.warehouseGoodsList;

    //遍历明细 给每一个对象增加属性show
    tmp.forEach(r => {
      r.show = {};
    })
    tableData.value = tmp;

    console.log(tableData.value);
  }
}


onMounted(() => {
  queryCategory();
  queryWarehouseName();
  init();
  getBatch(route.params.id);
});


</script>

<style scoped lang="scss">
.detail-title {
  height: 40px;
  line-height: 40px;
  border: #ebeef5 solid 1px;
  border-bottom-style: none;
  padding-left: 10px;
}

.detail {
  margin-top: 100px;
}
</style>
